// 文件预览组件 - 支持图片、视频、音乐预览
// 优化性能：懒加载、缓存、虚拟化

// 等待Vue加载完成后再初始化
(function() {
    // 检查Vue是否已加载
    if (typeof Vue === 'undefined') {
        console.error('Vue is not loaded');
        return;
    }
    
    const { ref, computed, onMounted, onUnmounted, nextTick } = Vue;

// 预览组件配置
const FilePreview = {
    name: 'FilePreview',
    template: `
        <div v-if="visible" class="file-preview-overlay" @click="handleOverlayClick">
            <div class="file-preview-container">
                <!-- 顶部控制栏 -->
                <div class="preview-header">
                    <div class="preview-title">{{ currentFile.file_name }}</div>
                    <div class="preview-controls">
                        <el-button v-if="isPrevDisabled" @click="prevFile" :disabled="isPrevDisabled" circle>
                            <el-icon><ArrowLeft /></el-icon>
                        </el-button>
                        <el-button v-if="isNextDisabled" @click="nextFile" :disabled="isNextDisabled" circle>
                            <el-icon><ArrowRight /></el-icon>
                        </el-button>
                        <el-button @click="closePreview" circle>
                            <el-icon><Close /></el-icon>
                        </el-button>
                    </div>
                </div>
                
                <!-- 预览内容区域 -->
                <div class="preview-content" ref="contentRef">
                    <!-- 图片预览 -->
                    <div v-if="isImage" class="image-preview-container">
                        <div class="image-wrapper" 
                             :style="imageWrapperStyle"
                             @mousedown="handleMouseDown"
                             @wheel="handleWheel"
                             ref="imageWrapperRef">
                            <img 
                                :src="currentFile.cover" 
                                :style="imageStyle"
                                @load="handleImageLoad"
                                @dragstart="preventDefault"
                                draggable="false"
                                ref="imageRef"
                                alt=""
                            />
                        </div>
                        <!-- 图片控制栏 -->
                        <div class="image-controls">
                            <el-button @click="zoomOut" :disabled="scale <= 0.1" circle>
                                <el-icon><ZoomOut /></el-icon>
                            </el-button>
                            <span class="zoom-info">{{ Math.round(scale * 100) }}%</span>
                            <el-button @click="zoomIn" :disabled="scale >= 5" circle>
                                <el-icon><ZoomIn /></el-icon>
                            </el-button>
                            <el-button @click="resetZoom" circle>
                                <el-icon><Refresh /></el-icon>
                            </el-button>
                            <el-button @click="toggleFullscreen" circle>
                                <el-icon><FullScreen /></el-icon>
                            </el-button>
                        </div>
                    </div>
                    
                    <!-- 视频预览 -->
                    <div v-else-if="isVideo" class="video-preview-container">
                        <video 
                            :src="currentFile.cover" 
                            controls 
                            preload="metadata"
                            @loadedmetadata="handleVideoLoad"
                            ref="videoRef">
                            您的浏览器不支持视频播放
                        </video>
                    </div>
                    
                    <!-- 音频预览 -->
                    <div v-else-if="isAudio" class="audio-preview-container">
                        <div class="audio-info">
                            <el-icon class="audio-icon"><Headphone /></el-icon>
                            <div class="audio-name">{{ currentFile.file_name }}</div>
                        </div>
                        <audio 
                            :src="currentFile.cover" 
                            controls 
                            preload="metadata"
                            @loadedmetadata="handleAudioLoad"
                            ref="audioRef">
                            您的浏览器不支持音频播放
                        </audio>
                    </div>
                    
                    <!-- 不支持的文件类型 -->
                    <div v-else class="unsupported-preview">
                        <el-icon class="unsupported-icon"><Document /></el-icon>
                        <div class="unsupported-text">不支持预览此文件类型</div>
                    </div>
                </div>
            </div>
        </div>
    `,
    props: {
        visible: Boolean,
        files: Array,
        currentIndex: Number
    },
    emits: ['update:visible', 'update:currentIndex'],
    setup(props, { emit }) {
        // 响应式数据
        const scale = ref(1);
        const translateX = ref(0);
        const translateY = ref(0);
        const isDragging = ref(false);
        const dragStart = ref({ x: 0, y: 0 });
        const imageLoaded = ref(false);
        
        // DOM引用
        const contentRef = ref(null);
        const imageWrapperRef = ref(null);
        const imageRef = ref(null);
        const videoRef = ref(null);
        const audioRef = ref(null);
        
        // 计算属性
        const currentFile = computed(() => {
            return props.files[props.currentIndex] || {};
        });
        
        const isImage = computed(() => {
            return currentFile.value.type === 1; // 图片类型
        });
        
        const isVideo = computed(() => {
            return currentFile.value.type === 7; // 视频类型
        });
        
        const isAudio = computed(() => {
            return currentFile.value.type === 6; // 音频类型
        });
        
        const isPrevDisabled = computed(() => {
            return props.currentIndex <= 0;
        });
        
        const isNextDisabled = computed(() => {
            return props.currentIndex >= props.files.length - 1;
        });
        
        const imageWrapperStyle = computed(() => {
            return {
                cursor: isDragging.value ? 'grabbing' : (scale.value > 1 ? 'grab' : 'default')
            };
        });
        
        const imageStyle = computed(() => {
            return {
                transform: `scale(${scale.value}) translate(${translateX.value}px, ${translateY.value}px)`,
                transition: isDragging.value ? 'none' : 'transform 0.3s ease',
                maxWidth: scale.value <= 1 ? '100%' : 'none',
                maxHeight: scale.value <= 1 ? '100%' : 'none'
            };
        });
        
        // 方法
        const closePreview = () => {
            emit('update:visible', false);
            resetZoom();
        };
        
        const prevFile = () => {
            if (!isPrevDisabled.value) {
                emit('update:currentIndex', props.currentIndex - 1);
                resetZoom();
            }
        };
        
        const nextFile = () => {
            if (!isNextDisabled.value) {
                emit('update:currentIndex', props.currentIndex + 1);
                resetZoom();
            }
        };
        
        const handleOverlayClick = (e) => {
            if (e.target === e.currentTarget) {
                closePreview();
            }
        };
        
        // 图片缩放功能
        const zoomIn = () => {
            if (scale.value < 5) {
                scale.value = Math.min(5, scale.value * 1.2);
            }
        };
        
        const zoomOut = () => {
            if (scale.value > 0.1) {
                scale.value = Math.max(0.1, scale.value / 1.2);
                // 如果缩放比例小于等于1，重置位移
                if (scale.value <= 1) {
                    translateX.value = 0;
                    translateY.value = 0;
                }
            }
        };
        
        const resetZoom = () => {
            scale.value = 1;
            translateX.value = 0;
            translateY.value = 0;
            imageLoaded.value = false;
        };
        
        const toggleFullscreen = async () => {
            if (!document.fullscreenElement) {
                await contentRef.value.requestFullscreen();
            } else {
                await document.exitFullscreen();
            }
        };
        
        // 滚轮缩放（优化性能）
        const handleWheel = window.optimizerUtils?.throttle ? window.optimizerUtils.throttle((e) => {
            if (!isImage.value || !imageLoaded.value) return;
            
            e.preventDefault();
            const delta = e.deltaY > 0 ? -1 : 1;
            const zoomFactor = 1 + (delta * 0.1);
            
            const newScale = Math.min(5, Math.max(0.1, scale.value * zoomFactor));
            
            if (newScale !== scale.value) {
                // 计算鼠标位置相对于图片的坐标
                const rect = imageRef.value.getBoundingClientRect();
                const centerX = rect.left + rect.width / 2;
                const centerY = rect.top + rect.height / 2;
                
                const mouseX = e.clientX - centerX;
                const mouseY = e.clientY - centerY;
                
                // 根据缩放中心调整位移
                const scaleRatio = newScale / scale.value;
                translateX.value = translateX.value * scaleRatio + mouseX * (1 - scaleRatio) / newScale;
                translateY.value = translateY.value * scaleRatio + mouseY * (1 - scaleRatio) / newScale;
                
                scale.value = newScale;
                
                // 如果缩放比例小于等于1，重置位移
                if (scale.value <= 1) {
                    translateX.value = 0;
                    translateY.value = 0;
                }
            }
        }, 16) : (e) => { // 60fps fallback
            if (!isImage.value || !imageLoaded.value) return;
            
            e.preventDefault();
            const delta = e.deltaY > 0 ? -1 : 1;
            const zoomFactor = 1 + (delta * 0.1);
            
            const newScale = Math.min(5, Math.max(0.1, scale.value * zoomFactor));
            
            if (newScale !== scale.value) {
                const rect = imageRef.value.getBoundingClientRect();
                const centerX = rect.left + rect.width / 2;
                const centerY = rect.top + rect.height / 2;
                
                const mouseX = e.clientX - centerX;
                const mouseY = e.clientY - centerY;
                
                const scaleRatio = newScale / scale.value;
                translateX.value = translateX.value * scaleRatio + mouseX * (1 - scaleRatio) / newScale;
                translateY.value = translateY.value * scaleRatio + mouseY * (1 - scaleRatio) / newScale;
                
                scale.value = newScale;
                
                if (scale.value <= 1) {
                    translateX.value = 0;
                    translateY.value = 0;
                }
            }
        };
        
        // 鼠标拖拽
        const handleMouseDown = (e) => {
            if (!isImage.value || scale.value <= 1) return;
            
            e.preventDefault();
            isDragging.value = true;
            dragStart.value = {
                x: e.clientX - translateX.value,
                y: e.clientY - translateY.value
            };
            
            document.addEventListener('mousemove', handleMouseMove);
            document.addEventListener('mouseup', handleMouseUp);
        };
        
        const handleMouseMove = (e) => {
            if (!isDragging.value) return;
            
            translateX.value = e.clientX - dragStart.value.x;
            translateY.value = e.clientY - dragStart.value.y;
        };
        
        const handleMouseUp = () => {
            isDragging.value = false;
            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', handleMouseUp);
        };
        
        // 防止默认拖拽行为
        const preventDefault = (e) => {
            e.preventDefault();
        };
        
        // 媒体加载事件
        const handleImageLoad = () => {
            imageLoaded.value = true;
            // 预加载相邻文件
            if (window.performanceOptimizer?.preloadAdjacent) {
                window.performanceOptimizer.preloadAdjacent(props.files, props.currentIndex);
            }
        };
        
        const handleVideoLoad = () => {
            console.log('Video loaded');
            // 预加载相邻文件
            if (window.performanceOptimizer?.preloadAdjacent) {
                window.performanceOptimizer.preloadAdjacent(props.files, props.currentIndex);
            }
        };
        
        const handleAudioLoad = () => {
            console.log('Audio loaded');
            // 预加载相邻文件
            if (window.performanceOptimizer?.preloadAdjacent) {
                window.performanceOptimizer.preloadAdjacent(props.files, props.currentIndex);
            }
        };
        
        // 键盘事件
        const handleKeyDown = (e) => {
            if (!props.visible) return;
            
            switch (e.key) {
                case 'Escape':
                    closePreview();
                    break;
                case 'ArrowLeft':
                    prevFile();
                    break;
                case 'ArrowRight':
                    nextFile();
                    break;
                case '+':
                case '=':
                    zoomIn();
                    break;
                case '-':
                case '_':
                    zoomOut();
                    break;
                case '0':
                    resetZoom();
                    break;
            }
        };
        
        // 生命周期
        onMounted(() => {
            document.addEventListener('keydown', handleKeyDown);
        });
        
        onUnmounted(() => {
            document.removeEventListener('keydown', handleKeyDown);
            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', handleMouseUp);
        });
        
        return {
            // 数据
            scale,
            translateX,
            translateY,
            isDragging,
            imageLoaded,
            
            // 引用
            contentRef,
            imageWrapperRef,
            imageRef,
            videoRef,
            audioRef,
            
            // 计算属性
            currentFile,
            isImage,
            isVideo,
            isAudio,
            isPrevDisabled,
            isNextDisabled,
            imageWrapperStyle,
            imageStyle,
            
            // 方法
            closePreview,
            prevFile,
            nextFile,
            handleOverlayClick,
            zoomIn,
            zoomOut,
            resetZoom,
            toggleFullscreen,
            handleWheel,
            handleMouseDown,
            preventDefault,
            handleImageLoad,
            handleVideoLoad,
            handleAudioLoad
        };
    }
};

// 导出组件供全局使用
window.FilePreview = FilePreview;

})(); // 结束立即执行函数